package com.yubest.client.config;

import com.google.gson.Gson;
import com.yubest.tool.MyLicenseVerifier;
import de.schlichtherle.license.LicenseManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author hweiyu
 * @Description
 * @Date 2022/6/16 9:43
 */
@Component
@Slf4j
public class LicenseInterceptor implements HandlerInterceptor {

    @Autowired
    private LicenseManager manager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        log.info("------开始校验证书------");
        try {
            new MyLicenseVerifier().verify(manager);
            return true;
        } catch (Exception e) {
            log.error("证书校验失败", e);
        }
        response.setCharacterEncoding("UTF-8");
        Map<String, Object> data = new HashMap<>();
        data.put("code", 1000);
        data.put("msg", "当前服务器不在授权范围内");
        response.getWriter().write(new Gson().toJson(data));
        return false;
    }
}
